﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System.Collections.Generic;
using System.IO;

namespace DNA.Mvc.Installation
{
    public class FilesInstaller : InstallerBase
    {
        public override string Name
        {
            get { return "files"; }
        }

        public override void Execute(InstallationContext context)
        {
            //string appPath = HttpContext != null ? HttpContext.Server.MapPath(context.Data["AppPath"].ToString()) : context.Data["AppPath"].ToString();
            var appPath = context.HttpContext.Server.MapPath(context.HttpContext.Request.ApplicationPath);
            var execPath = ExecutionPath + "\\content\\";
            var webName = context.Data["Web.Name"].ToString();

            if (!Directory.Exists(execPath)) throw new DirectoryNotFoundException();

            var dirs = Directory.GetDirectories(execPath);
            
            context.Trace.Warn("This installer will copy files to your appliaction.");
            
            CopyPath(context.Trace, execPath, appPath, webName, dirs);
        }

        private void CopyPath(TraceContext trace, string srcPath, string distPath, string webName, string[] dirs)
        {
            foreach (var dir in dirs)
            {
                var targetPath = GetTargetPath(srcPath,distPath, webName, dir);

                if (!Directory.Exists(targetPath))
                {
                    trace.Write("Creating directiroy \""+targetPath+"\"");
                    Directory.CreateDirectory(targetPath);
                }

                var files = Directory.GetFiles(dir);
                foreach (var file in files)
                {
                    var targetFile = GetTargetPath(srcPath, distPath, webName, file);

                    trace.Write("Copying file \"" + targetFile + "\"");

                    File.Copy(file, targetFile, true);
                }

                var subDirs = Directory.GetDirectories(dir);

                if (subDirs.Length > 0)
                    CopyPath(trace,srcPath, distPath, webName, subDirs);
            }
        }

        private string GetTargetPath(string srcPath, string distPath, string webName, string dir)
        {
            var _subPath = dir.Replace(srcPath, "");

            if (_subPath.IndexOf("\\_user_") > -1)
            {
                if (webName.Equals("home",System.StringComparison.OrdinalIgnoreCase))
                    _subPath=_subPath.Replace("\\_user_", "\\public");
                else
                _subPath = _subPath.Replace("\\_user_", "\\personal\\" + webName);
            }

            var _path =distPath + _subPath;
            
            if (!distPath.EndsWith("\\") && !_subPath.StartsWith("\\"))
                _path=distPath +"\\"+ _subPath;

            return _path;
        }
    }
}
